<template>
  <!-- 购物车界面 -->
  <div class="cart" ref="my_cart">
    <!-- 顶部标签 -->
    <van-nav-bar title="购物车" left-arrow @click-left="onClickLeft" :fixed="true" :placeholder="true" />
    <!-- 购物车内容 -->
    <div v-if="stas==0">
      <div v-if="data.length!=0">
        <van-swipe-cell v-for="(item,index) in data" :key="index+'px'">
          <van-card :num="item.select_num" :price="((item.price-0)*item.select_num).toFixed(2)" :desc="item.text"
            :title="item.name" :thumb="item.imgs[0]?item.imgs[0].url:this.$url +'img/redmi9.jpg'">

            <template #footer>
              <van-stepper v-model="item.select_num" @plus="data_change(index)" @minus="data_change(index)" />
            </template>
          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="delect_cart(item.id)" />
          </template>
          <van-divider />
        </van-swipe-cell>
      </div>
      <!-- 购物车为空时显示 -->
      <div v-else>
        <van-empty description="购物车空空如也" />
      </div>
    </div>
    <div v-else>
      <p class="one">
        <van-empty description="请先登录">
        </van-empty>
      </p>
    </div>
    <h4>猜你喜欢</h4>

    <van-grid :column-num="2" :gutter="10">
      <van-grid-item v-for="(value,index) in data_base.slice(2,16)" :key="index" @click="to_shopping(value)">
        <van-image :src="value.imgs[0]?value.imgs[0].url:this.$url +'img/redmi9.jpg'">
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
        </van-image>
        <p class="two">{{value.name}}</p>
        <!-- <p class="two" style="color:red">￥{{value.price}}</p> -->
      </van-grid-item>
    </van-grid>
    <van-submit-bar :price="money" button-text="提交订单" @submit="onSubmit" />
    <van-popup v-model="show" position="right" :style="{ width: '100%',height:'101%' }">
      <shopping v-on:exit="show=false" :data_base='form'></shopping>
    </van-popup>
  </div>

</template>
<script>
import shopping from "./shopping.vue";
export default {
  components: { shopping },
  data() {
    return {
      stas: 0,
      data: [],
      order: {
        sx: 1,
        id: [],
      },
      data_base: [],
      show: false,
      form: "",
    };
  },
  methods: {
    //查看图片
    to_shopping(a) {
      this.form = a;
      this.show = true;
    },
    //将cart的数据添加到订单中
    add_order(data_base, a) {
      let data_order = {
        user_id: data_base.user_id,
        goods_id: data_base.goods_id,
        address_id: a,
        select_num: data_base.select_num,
        is_payment: false,
        is_deliver: false,
        is_get: false,
        estimate: "",
        is_refund: false,
        is_to_refund: false,
      };
      let myurl = this.$url + "order_add";
      this.axios.post(myurl, { data_order }).then(
        (res) => {
          this.order.id.push(JSON.parse(res.data.data).insertId);
          let order = JSON.stringify(this.order);
          localStorage.setItem("order", order);
        },
        (err) => {
          console.log("数据读取失败");
          console.log(err);
        }
      );
    },
    //返回上一级
    onClickLeft() {
      this.$router.go(-1);
    },
    //结算
    onSubmit() {
      let address = localStorage.getItem("address");
      address = JSON.parse(address);
      if (address.sx == 1) {
        for (let i = 0; i < this.data.length; i++) {
          this.add_order(this.data[i], address.id);
          this.delect_cart(this.data[i].id);
        }
        this.$router.push("/buy");
      } else {
        this.$toast.fail("请先填写收货地址");
      }
    },
    //刷新界面方法(获取数据)
    getDate() {
      let sta = localStorage.getItem("sta");
      sta = JSON.parse(sta);
      //读取用户信息
      let myurl = this.$url + "cart_read";
      this.axios.post(myurl, { id: sta.id }).then(
        (res) => {
          let a = res.data.data;
          a = a.replace(/\\/g, "");
          a = a.replace(/:"\[/g, ":[");
          a = a.replace(/\]"/g, "]");
          a = JSON.parse(a);
          this.data = a;
        },
        (err1) => {
          console.log("数据读取失败");
          console.log(err1);
        }
      );
    },
    //获取商品数据
    getDate1() {
      //读取商品信息
      let myurl = this.$url + "goods_read";
      this.axios.post(myurl).then(
        (res) => {
          let a = res.data.data;
          a = a.replace(/\\/g, "");
          a = a.replace(/:"\[/g, ":[");
          a = a.replace(/\]"/g, "]");
          a = JSON.parse(a);
          this.data_base = a;
        },
        (err) => {
          console.log("数据读取失败");
          console.log(err);
        }
      );
    },
    //删除按钮
    delect_cart(a) {
      let myur = this.$url + "cart_delete";
      this.axios.post(myur, { id: a }).then(
        () => {
          this.$toast("操作成功");
          this.getDate();
        },
        (err) => {
          console.log("数据读取失败");
          console.log(err);
        }
      );
    },
    //步进器按钮，修改购物车商品数量
    data_change(index) {
      let myur = this.$url + "cart_change";
      this.$nextTick(function () {
        let data_cart = {
          id: this.data[index].id,
          select_num: this.data[index].select_num,
        };
        this.axios.post(myur, { data_cart });
      });
    },
  },
  //将结算栏固定在底部
  mounted() {
    let a = document.querySelector(".van-tabbar").offsetHeight;
    document.querySelector(".van-submit-bar").style.bottom = a + "px";
  },
  //刷新界面
  created() {
    let sta = localStorage.getItem("sta");
    if (sta) {
      sta = JSON.parse(sta);
      if (sta.sx == 1) {
        this.stas = 0;
        this.getDate();
      } else {
        this.stas = 1;
      }
    }
    this.getDate1();
    this.$nextTick(function () {
      this.$forceUpdate();
    });
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      let sta = localStorage.getItem("sta");
      if (sta) {
        sta = JSON.parse(sta);
        if (sta.sx == 1) {
          vm.stas = 0;
          vm.getDate();
        } else {
          vm.stas = 1;
        }
      }
      vm.getDate1();
      vm.$nextTick(function () {
        vm.$forceUpdate();
      });
    });
  },
  //计算购物车总价格
  computed: {
    money() {
      let num = 0;
      for (let i = 0; i < this.data.length; i++) {
        num += (this.data[i].price - 0) * this.data[i].select_num * 100;
      }
      return num;
    },
  },
};
</script>
<style scoped>
.cart {
  height: 100%;
  overflow: auto;
}
.cart::-webkit-scrollbar {
  display: none;
}
.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}
.van-submit-bar {
  position: fixed;
}
.one {
  text-align: center;
  margin: 20%;
  color: rgba(0, 0, 0, 0.3);
}
.two {
  margin: 0;
}
</style>